package com.tticar.invmanager.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.entity.Columns;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tticar.invmanager.common.Enum.CodeType;
import com.tticar.invmanager.common.Enum.Status;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.common.utils.PinYinUtil;
import com.tticar.invmanager.common.utils.ServiceUtil;
import com.tticar.invmanager.common.utils.tree.TreeUtils;
import com.tticar.invmanager.entity.*;
import com.tticar.invmanager.entity.vo.*;
import com.tticar.invmanager.mapper.MMaterielMapper;
import com.tticar.invmanager.mapper.MMaterielSkuMapper;
import com.tticar.invmanager.service.*;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 存货表 服务实现类
 * </p>
 *
 * @author joeyYan
 * @since 2018-07-09
 */
@Service
public class MMaterielServiceImpl extends ServiceImpl<MMaterielMapper, MMateriel> implements IMMaterielService {

    @Autowired
    private ICodeCounterService codeCounterService;
    @Autowired
    private IMCateogryService cateogryService;
    @Autowired
    private IMBrandService brandService;
    @Autowired
    private IWWearhouseService wearhouseService;
    @Autowired
    private IWPositionService positionService;
    @Autowired
    private IWRelativeUnitService relativeUnitService;
    @Autowired
    private IMMaterielSkuService mMaterielSkuService;
    @Autowired
    private IRepositoryCountService repositoryCountService;
    @Autowired
    private IWPositionMaterielService positionMaterielService;
    @Autowired
    private IInRepositoryDetailService repositoryDetailService;
    @Autowired
    private ICarBrandMaterielService carBrandMaterielService;
    @Autowired
    private MMaterielSkuMapper mMaterielSkuMapper;

    private final int codeLength = 5;

    @Override
    public Page selectPage(MMateriel mMateriel, MyPage<MMateriel> page) {
        Wrapper w = Condition.create().addFilter("1=1");
        if (mMateriel.getCategoryId() != null && mMateriel.getCategoryId() != 0) {
            List list = new ArrayList<>();
            list.add(mMateriel.getCategoryId());
            List ids = ServiceUtil.getCateogryIdList(list, cateogryService, true);
            w.in("t1." + MMateriel.CATEGORY_ID, ids);
        }
        if (Strings.isNotEmpty(mMateriel.getName())) {
            w.like("t1." + MMateriel.NAME, mMateriel.getName());
//            w.or().like("t." + MMaterielSku.CODE, mMateriel.getName());
//            w.or().like("t." + MMaterielSku.PARTSCODE, mMateriel.getName());
        }
        w.like(Strings.isNotEmpty(mMateriel.getCar()), "t1." + MMateriel.CAR, mMateriel.getCar());
        w.orderBy("t1.ctime desc, t1.name asc");

        List<Map> list = baseMapper.getPage(page, w);
        return page.setRecords(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids) {
        List list = new ArrayList();
        for (Long id : ids) {
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("materiel_id", id);
            positionMaterielService.delete(wrapper);
            MMateriel mMateriel = new MMateriel();
            mMateriel.setId(id);
            //删除为-1，区分删除和禁用
            mMateriel.setStatus(-1);
            list.add(mMateriel);
        }
        this.updateBatchById(list);
        MMaterielSku materielSku = new MMaterielSku();
        materielSku.setStatus(-1);
        Wrapper w = new EntityWrapper();
        w.in(MMaterielSku.MID, ids);
        mMaterielSkuService.update(materielSku, w);
        List<MMaterielSku> mMaterielSkus = mMaterielSkuService.selectList(w);
        List skuIds = new ArrayList<>();
        if (mMaterielSkus != null && mMaterielSkus.size() > 0) {
            for (MMaterielSku sku : mMaterielSkus) {
                skuIds.add(sku.getId());
            }
        }
        //删除关联关系
        mMaterielSkuMapper.deleteRelativeBySkuIds(skuIds);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(MMateriel mMateriel, List<MMaterielSku> mMaterielSkus, String house, List<CarBrandMateriel> carBrandList) {
        if (CollectionUtils.isEmpty(mMaterielSkus)) return;
        mMateriel.setNameSpell(PinYinUtil.getFirstLetter(mMateriel.getName()));
        mMateriel.setPinyin(PinYinUtil.getPinyinString(mMateriel.getName()));
        mMateriel.setInitials(PinYinUtil.getFirstLetters(mMateriel.getName(), HanyuPinyinCaseType.LOWERCASE));

        List<WPositionMateriel> pmList = new ArrayList<>();
        if (StringUtils.isNotEmpty(house)) {
            String[] arr = house.split(",");
            for (String tmp : arr) {
                String[] arr2 = tmp.split("_");
                Long wearhouseId = Long.valueOf(arr2[2]);
                Long positionId = Long.valueOf(arr2[0]);
                Integer isDefault = Integer.valueOf(arr2[4]);
                if (isDefault == 1) {
                    mMateriel.setDefaultWhouseId(wearhouseId);
                    mMateriel.setDefaultPositionId(positionId);
                }

                WPositionMateriel pm = new WPositionMateriel();
                pm.setWearhouseId(wearhouseId);
                pm.setPositionId(positionId);
                pm.setIsDefault(isDefault);
                pmList.add(pm);
            }
        }

        // 重新编辑时候释放原来所占库位
        if (mMateriel.getId() != null && mMateriel.getId() != 0) {
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("materiel_id", mMateriel.getId());
            this.positionMaterielService.delete(wrapper);

            //清除绑定车型
            this.carBrandMaterielService.delete(wrapper);
        }

        String carInfo = "";
        for (CarBrandMateriel cbm : carBrandList) {
            JSONArray arr = JSONObject.parseArray(cbm.getCar());
            String car = "";
            for (int i = 0; i < arr.size(); i++) {
                car += " -> " + arr.getJSONObject(i).getString("name");
            }
            carInfo += car.substring(4);
            if (StringUtils.isNotEmpty(cbm.getYear())) {
                carInfo += " " + cbm.getYear() + ",";
            }
        }
        if (!carInfo.equals("")) {
            carInfo = carInfo.substring(0, carInfo.length());
        }
        mMateriel.setCar(carInfo);

        this.insertOrUpdate(mMateriel);

        //重新绑定车型
        for (CarBrandMateriel cbm : carBrandList) {
            cbm.setMaterielId(mMateriel.getId());
            cbm.setTenantId(null);
            cbm.setCtime(new Date());
            this.carBrandMaterielService.insert(cbm);
        }

        // 占库位
        for (WPositionMateriel pm : pmList) {
            pm.setMaterielId(mMateriel.getId());
            this.positionMaterielService.insert(pm);
        }

        // 规格新加的新增，减少的删除，其他的不改变code更新
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq(MMaterielSku.MID, mMateriel.getId());
        wrapper.eq("status", 0);
        List<MMaterielSku> allSkuList = mMaterielSkuService.selectList(wrapper);
        List<MMaterielSku> editorList = new ArrayList<>();
        for (MMaterielSku materielSku : mMaterielSkus) {
            materielSku.setStatus(mMateriel.getStatus());
            if (materielSku.getId() == null || materielSku.getId() == 0) {
                // 规格新加的新增
                materielSku.setTenantId(null);
                materielSku.setMid(mMateriel.getId());
                if (mMateriel.getCategoryId() == null) {
                    throw new MyServiceException("分类不能为空");
                }
                materielSku.setCode(codeCounterService.getCode(CodeType.SP, mMateriel.getCategoryId().toString(), codeLength));
                mMaterielSkuService.insert(materielSku);

                //加规格要增加一个库存量为0 方便盘点0库存的
                RepositoryCount repositoryCount = new RepositoryCount();
                repositoryCount.setWearhouseId(mMateriel.getDefaultWhouseId());
                repositoryCount.setSkuId(materielSku.getId());
                repositoryCount.setCount(0);
                repositoryCountService.insert(repositoryCount);
            } else {
                editorList.add(materielSku); // 被编辑的和删除的
            }
        }

        if (CollectionUtils.isNotEmpty(allSkuList)) {
            for (MMaterielSku materielSku : allSkuList) {
                if (CollectionUtils.isEmpty(editorList)) {
                    // 提交的如果为空，则原有的全部删除
                    MMaterielSku updater = new MMaterielSku();
                    updater.setId(materielSku.getId());
                    updater.setStatus(Status.DELETE.getCode());
                    mMaterielSkuService.updateById(updater);
                    continue;
                }
                for (int i = 0; i < editorList.size(); i++) {
                    MMaterielSku editor = editorList.get(i);
                    // 已存在的 更新
                    if (editor.getId().equals(materielSku.getId())) {
                        editorList.add(editor);
                        mMaterielSkuService.updateById(editor);
                        break;
                    }
                    if (i == editorList.size() - 1) {
                        // 编辑后的规格对比编辑前的，没有的的删除
                        MMaterielSku updater = new MMaterielSku();
                        updater.setId(materielSku.getId());
                        updater.setStatus(Status.DELETE.getCode());
                        mMaterielSkuService.updateById(updater);
                    }
                }
            }
        }
    }

    @Override
    public Object getById(Long id) {
        Map map = this.selectMap(Condition.create().eq(MMateriel.ID, id));
        Wrapper w1 = new EntityWrapper<>();
        w1.eq("id", map.get("categoryId"));
        MCateogry mCateogry = cateogryService.selectOne(w1);
        if (mCateogry != null && mCateogry.getName() != null) {
            map.put("categoryName", mCateogry.getName());
        }
        Wrapper<MMaterielSku> w = Condition.create().eq(MMaterielSku.MID, id);
        w.ne("status", Status.DELETE.getCode());
//        w.setSqlSelect(MMaterielSku.ID, MMaterielSku.PRICES, MMaterielSku.SKUS);
        List mskus = mMaterielSkuService.selectMaps(w);
        map.put("mSkus", mskus);
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(MMaterielSku mMaterielSku) {
        mMaterielSkuService.updateById(mMaterielSku);
        //更新主表库存
//        Wrapper<MMaterielSku> w = Condition.create().eq(MMaterielSku.MID, mMaterielSku.getMid());
//        w.setSqlSelect("sum(inventory)");
//        Object ainventory = mMaterielSkuService.selectObj(w);
        //
//        MMateriel mMateriel = new MMateriel();
//        mMateriel.setId(mMaterielSku.getMid());
//        this.updateById(mMateriel);
    }

    @Override
    public Page list(MMateriel mMateriel, MyPage<MMateriel> page) {
        Wrapper w = Condition.create().eq(MMateriel.STATUS, MMateriel.ZERO);
        w.orderBy(Strings.isNotEmpty(page.getOrder()), page.getSort(), page.sort()).orderBy(MMateriel.CTIME, false);
        Columns columns = Columns.create().column("*");
        columns.column("(select name from m_cateogry where id=category_id)", "categoryName");
        columns.column("(select name from m_brand where id=brand_id)", "brandName");
        columns.column("(select count(1) from m_materiel_tticar where materiel_id=m_materiel.id)", "isTticar");
        columns.column("(select name from w_relative_unit where id=default_uint_id)", "ralativeName");
        columns.column("(select name from w_wearhouse where id=default_whouse_id)", "wearhouseName");
        w.setSqlSelect(columns);
        w.like(!StringUtils.isEmpty(mMateriel.getName()), MMateriel.NAME, mMateriel.getName());
        this.selectMapsPage(page, w);
        for (Object obj : page.getRecords()) {
            Map map = (Map) obj;
            Wrapper<MMaterielSku> ww = Condition.create().eq(MMaterielSku.MID, MapUtils.getLong(map, MMateriel.ID));
            ww.eq("status", 0);
            map.put("mSkus", mMaterielSkuService.selectMaps(ww));
        }
        return page;
    }

    @Override
    public List<Tree> tree(Long pid, Integer type) {
        List<Tree> resultList = new ArrayList<>();
        if (pid == null || pid == 0) {
            List<Map> list = baseMapper.getForTree(null);
            for (Map map : list) {
                Tree tree = new Tree((Long) map.get("id"), (String) map.get("name"));
                tree.setState("closed");
                tree.setPid(0l);
                tree.setIconCls("icon-goods");

                Map<String, Object> attr = new HashMap<>();
                attr.put("unit", map.get("unit"));
                attr.put("ralativeId", map.get("ralativeId"));
                attr.put("ralativeName", map.get("ralativeName"));
                attr.put("wearhouseId", map.get("wearhouseId"));
                attr.put("wearhouseName", map.get("wearhouseName"));
                attr.put("positionId", map.get("positionId"));
                attr.put("positionName", map.get("positionName"));
                attr.put("car", map.get("car"));

                tree.setAttributes(attr);
                resultList.add(tree);
            }
        } else {
            Wrapper<MMaterielSku> ww = Condition.create().eq(MMaterielSku.MID, pid);
            ww.eq("status", 0);
            List<Map<String, Object>> list = mMaterielSkuService.selectMaps(ww);

            if (list.size() != 0) {
                String skuIds = "";
                for (Map map : list) {
                    skuIds += "," + map.get("id");

                    Tree tree = new Tree((Long) map.get("id"), (String) map.get("skus"));
                    tree.setIconCls("icon-sku");
                    tree.setState("open");
                    tree.setPid(pid);

                    Map<String, Object> attr = new HashMap<>();
                    attr.put("amount", map.get("buyPrice") == null ? "0" : map.get("buyPrice"));
                    attr.put("salesAmout", map.get("sellPrice") == null ? "0" : map.get("sellPrice"));
                    attr.put("code", map.get("code"));
                    tree.setAttributes(attr);
                    resultList.add(tree);
                }

                skuIds = skuIds.substring(1);

                //库存数量
                List<Map> skuList = repositoryCountService.getSkuNum(skuIds);
                Map<Long, BigDecimal> skuMap = new HashMap<>();
                for (Map<String, Object> tmp : skuList) {
                    skuMap.put((Long) tmp.get("skuId"), (BigDecimal) tmp.get("skuNum"));
                }
                for (Tree tree : resultList) {
                    tree.getAttributes().put("skusNum", skuMap.get(tree.getId()) == null ? 0 : skuMap.get(tree.getId()).intValue());
                }

                if (type == 0) {
                    //最早批次
                    List<Map> batchList = repositoryDetailService.getSkuBatchCodeForOut(skuIds);
                    Map<String, String> batchMap = new HashMap<>();
                    for (Map<String, Object> tmp : batchList) {
                        batchMap.put(tmp.get("skuId").toString(), (String) tmp.get("house"));
                    }
                    for (Tree tree : resultList) {
                        tree.getAttributes().put("house", batchMap.get(tree.getId().toString()) == null ? "" : batchMap.get(tree.getId().toString()));
                    }
                }
            }
        }

        return resultList;
    }

    @Override
    public List<Tree> tree(String searchText, Integer type) {
        List<Tree> resultList = new ArrayList<>();
        List<Map> list = baseMapper.getForTree(searchText);
        for (Map map : list) {
            Tree tree = new Tree((Long) map.get("id"), (String) map.get("name"));
            tree.setState("open");
            tree.setPid(0l);
            tree.setIconCls("icon-goods");

            Map<String, Object> attr = new HashMap<>();
            attr.put("unit", map.get("unit"));
            attr.put("ralativeId", map.get("ralativeId"));
            attr.put("ralativeName", map.get("ralativeName"));
            attr.put("wearhouseId", map.get("wearhouseId"));
            attr.put("wearhouseName", map.get("wearhouseName"));
            attr.put("positionId", map.get("positionId"));
            attr.put("positionName", map.get("positionName"));
            attr.put("car", map.get("car"));
            tree.setAttributes(attr);

            List<Tree> children = tree((Long) map.get("id"), type);
            if (children != null && children.size() > 0) {
                tree.setChildren(children);
                resultList.add(tree);
            }
        }

        return resultList;
    }

    @Override
    public List<Long> selectMaterielIdByName(String materielName) {
        return baseMapper.selectSkuIdByMaterielName(materielName);
    }

    @Override
    public List<GoodsTreeGrid> treegridForCheck(GoodsTreeGridSearchDto searchDto) {
        List<GoodsTreeGrid> resultList = new ArrayList<>();
        if (searchDto.getId() == null) {//商品
            if (searchDto.getCategoryId() != null) {
                Long categoryId = Long.valueOf(searchDto.getCategoryId());
                if (categoryId == 0) {
                    searchDto.setCategoryId(null);
                } else {
                    MCateogry cateogry = this.cateogryService.selectById(categoryId);

                    if (cateogry.getCategoryType() == 2) {
                        String cateIds = "";
                        Wrapper ww = Condition.create().eq("pid", categoryId);
                        List<MCateogry> cateList = this.cateogryService.selectList(ww);
                        for (MCateogry cate : cateList) {
                            cateIds += "," + cate.getId();
                        }
                        if (cateIds != "") {
                            cateIds = cateIds.substring(1);
                        }
                        searchDto.setCategoryId(cateIds);
                    } else if (cateogry.getCategoryType() == 1) {
                        List<Long> idList = new ArrayList<>();
                        Wrapper ww = Condition.create().eq("pid", categoryId);
                        List<MCateogry> cateList = this.cateogryService.selectList(ww);
                        for (MCateogry cate : cateList) {
                            idList.add(cate.getId());
                        }
                        if (idList.size() > 0) {
                            String cateIds = "";
                            ww = Condition.create().in("pid", idList);
                            cateList = this.cateogryService.selectList(ww);
                            for (MCateogry cate : cateList) {
                                cateIds += "," + cate.getId();
                            }
                            if (cateIds != "") {
                                cateIds = cateIds.substring(1);
                            }
                            searchDto.setCategoryId(cateIds);
                        }
                    }
                }
            }

            List<Map> list = this.baseMapper.treegridForCheck(searchDto);
            Long[] ids = new Long[list.size()];
            for (int i = 0; i < list.size(); i++) {
                Map map = list.get(i);
                GoodsTreeGrid tree = new GoodsTreeGrid(map.get("id") + "", map.get("name") + "", map.get("categoryName") + "");
                tree.setState(StringUtils.isNotEmpty(searchDto.getSearchText()) ? "open" : "closed");
                tree.setIconCls("icon-goods");
                tree.setPid("0");
                resultList.add(tree);

                ids[i] = (Long) map.get("id");
            }
            if (StringUtils.isNotEmpty(searchDto.getSearchText())) {
                Wrapper<MMaterielSku> ww = Condition.create().in(MMaterielSku.MID, ids);
                List<Map<String, Object>> subList = mMaterielSkuService.selectMaps(ww);
                for (Map map : subList) {
                    GoodsTreeGrid tree = new GoodsTreeGrid("s" + map.get("id"), map.get("skus") + "", "");
                    tree.setPid(map.get("mid") + "");
                    tree.setState("open");
                    tree.setIconCls("icon-sku");
                    resultList.add(tree);
                }
                GoodsTreeGrid root = new GoodsTreeGrid("0", "全部", "");
                resultList.add(root);
                TreeUtils.createTree(resultList, root, "id", "pid", "children");
                resultList = root.getChildren();
            }
        } else { //规格
            Wrapper<MMaterielSku> ww = Condition.create().eq(MMaterielSku.MID, searchDto.getId());
            List<Map<String, Object>> list = mMaterielSkuService.selectMaps(ww);
            for (Map map : list) {
                GoodsTreeGrid tree = new GoodsTreeGrid("s" + map.get("id"), map.get("skus") + "", "");
                tree.setPid(map.get("mid") + "");
                tree.setState("open");
                tree.setIconCls("icon-sku");
                resultList.add(tree);
            }
        }
        return resultList == null ? new ArrayList<>() : resultList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importExcel(List<List<String>> list) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        checkIsNull(list);
        // 遍历excel数据
        for (int i = 0; i < list.size(); i++) {
            try {
                List<String> row = list.get(i);
                if (StringUtils.isBlank(row.get(0))) {
                    continue;
                }
                Wrapper wrapper = new EntityWrapper<>();
                wrapper.eq("name", row.get(0));
                wrapper.ne("status", -1);
                // 创建商品
                MMateriel materiel = this.selectOne(wrapper);
                if (materiel == null) {
                    materiel = new MMateriel();
                    materiel.setName(row.get(0));

                    Wrapper w1 = new EntityWrapper<>();
                    w1.eq("name", row.get(1));
                    w1.ne("pid", 0);
                    w1.ne("status", -1);
                    MCateogry cateogry = cateogryService.selectOne(w1);
                    if (cateogry == null) {
                        throw new MyServiceException("第" + (i + 2) + "行，系统中没有此分类，请先创建");
                    }
                    materiel.setCategoryId(cateogry.getId());

                    Wrapper w2 = new EntityWrapper<>();
                    w2.eq("name", row.get(2));
                    w2.ne("status", -1);
                    MBrand brand = brandService.selectOne(w2);
                    if (brand == null) {
                        brand = new MBrand();
                        brand.setName(row.get(2));
                        brandService.insert(brand);
                    }
                    materiel.setBrandId(brand.getId());

                    Wrapper w3 = new EntityWrapper<>();
                    w3.eq("name", row.get(3));
                    w3.eq("rproperty", 2);
                    w3.ne("status", -1);
                    WRelativeUnit relativeUnit = relativeUnitService.selectOne(w3);
                    if (relativeUnit == null) {
                        throw new MyServiceException("第" + (i + 2) + "行，系统中没有此供应商，请先创建");
                    }
                    materiel.setDefaultUintId(relativeUnit.getId());
                    materiel.setMinInventory(StringUtils.isBlank(row.get(6)) ? null : Integer.parseInt(row.get(6)));
                    materiel.setMaxInventory(StringUtils.isBlank(row.get(7)) ? null : Integer.parseInt(row.get(7)));
                    materiel.setmUnit(row.get(8));
                }
                // 仓库
                Wrapper w4 = new EntityWrapper<>();
                w4.eq("name", row.get(4));
                w4.ne("status", -1);
                WWearhouse wearhouse = wearhouseService.selectOne(w4);
                if (wearhouse == null) {
                    throw new MyServiceException("第" + (i + 2) + "行，系统中没有此仓库，请先创建");
                }
                // 库位
                Wrapper w5 = new EntityWrapper<>();
                w5.eq("name", row.get(5));
                w5.eq("wearhouse_id", wearhouse.getId());
                w5.ne("status", -1);
                WPosition position = positionService.selectOne(w5);
                boolean positionMaterielIsAdd = false;
                if (position == null) {
                    position = new WPosition();
                    position.setCode(codeCounterService.getCode(CodeType.KW, wearhouse.getId().toString(), 5));
                    position.setWearhouseId(wearhouse.getId());
                    position.setName(row.get(5));
                    positionService.insert(position);
                    positionMaterielIsAdd = true;
                } else {
                    Wrapper w = new EntityWrapper<>();
                    w.eq("wearhouse_id", wearhouse.getId());
                    w.eq("position_id", position.getId());
                    w.ne("status", -1);
                    WPositionMateriel positionMateriel = positionMaterielService.selectOne(w);
                    if (positionMateriel == null) {
                        positionMaterielIsAdd = true;
                    }
//                    else if (!positionMateriel.getMaterielId().equals(materiel.getId())) {
//                        throw new MyServiceException("第" + (i + 2) + "行，库位已被占用，同一库位只能放同一商品");
//                    }
                }
                if (materiel.getId() == null || materiel.getId() == 0) {
                    materiel.setDefaultWhouseId(wearhouse.getId());
                    materiel.setDefaultPositionId(position.getId());
                    this.insert(materiel);
                }
                // 增加库位
                if (positionMaterielIsAdd) {
                    WPositionMateriel positionMateriel = new WPositionMateriel();
                    positionMateriel.setIsDefault(1);
                    positionMateriel.setWearhouseId(wearhouse.getId());
                    positionMateriel.setPositionId(position.getId());
                    positionMateriel.setMaterielId(materiel.getId());
                    positionMaterielService.insert(positionMateriel);
                }
                // 创建商品sku
                MMaterielSku materielSku = new MMaterielSku();
                materielSku.setMid(materiel.getId());
//                materielSku.setCode(codeCounterService.getCode(CodeType.SP, materiel.getCategoryId().toString(), codeLength));
                materielSku.setCode(codeCounterService.getCode(CodeType.SP, null, codeLength)); //更改需求变为不需要带分类号
                materielSku.setSkus(row.get(9));
                // 配件编码
                materielSku.setPartsCode(row.get(10));
                // 售价/进价
                String str = row.get(10);
                materielSku.setBuyPrice(StringUtils.isBlank(row.get(11)) ? null : new BigDecimal(row.get(11)));
                materielSku.setSellPrice(StringUtils.isBlank(row.get(12)) ? null : new BigDecimal(row.get(12)));

                // 校验价格体系
                List<BigDecimal> priceList = new ArrayList<>();
                if (StringUtils.isNoneBlank(row.get(13))) priceList.add(new BigDecimal(row.get(13)));
                if (StringUtils.isNoneBlank(row.get(14))) priceList.add(new BigDecimal(row.get(14)));
                if (StringUtils.isNoneBlank(row.get(15))) priceList.add(new BigDecimal(row.get(15)));
                if (StringUtils.isNoneBlank(row.get(16))) priceList.add(new BigDecimal(row.get(16)));
                if (priceList.size() > 1) {
                    for (int j = 0; j < priceList.size() - 1; j++) {
                        if (priceList.get(j).compareTo(priceList.get(j + 1)) < 0) {
                            throw new MyServiceException("要求：批发价>=一级会员价>=二级会员价>=三级会员价");
                        }
                    }
                }
                Map<String, String> priceMap = new HashMap<>();
                priceMap.put("0", row.get(13));
                priceMap.put("1", row.get(14));
                priceMap.put("2", row.get(15));
                priceMap.put("3", row.get(16));
                materielSku.setPrices(JSON.toJSONString(priceMap));

                mMaterielSkuService.insert(materielSku);
            } catch (NumberFormatException nfe) {
                nfe.printStackTrace();
                throw new MyServiceException("导入的数据格式有误，请检查excel（如：该填写数字的地方必须填数字）");
            }
        }
    }

    private void checkIsNull(List<List<String>> list) {
        for (int i = 0; i < list.size(); i++) {
            List<String> row = list.get(i);
            if (StringUtils.isBlank(row.get(0))) {
                continue;
//                throw new MyServiceException("第"+ (i+2) + "行，存货名称不能为空");
            }
            if (StringUtils.isBlank(row.get(1))) {
                throw new MyServiceException("第" + (i + 2) + "行，分类不能为空");
            }
            if (StringUtils.isBlank(row.get(2))) {
                throw new MyServiceException("第" + (i + 2) + "行，品牌不能为空");
            }
            if (StringUtils.isBlank(row.get(3))) {
                throw new MyServiceException("第" + (i + 2) + "行，供应商不能为空");
            }
            if (StringUtils.isBlank(row.get(4)) || StringUtils.isBlank(row.get(5))) {
                throw new MyServiceException("第" + (i + 2) + "行，仓库/库位不能为空");
            }
            if (StringUtils.isBlank(row.get(9))) {
                throw new MyServiceException("第" + (i + 2) + "行，规格/尺寸不能为空");
            }
        }
    }

    @Override
    public Page search(MyPage<MMateriel> page, String searchText, String searchCar, Long houseId, Long bindHouseId) {
        Map<String, Object> params = new HashMap<>();
        params.put("searchText", searchText);
        params.put("searchCar", searchCar);
        params.put("houseId", houseId);
        params.put("bindHouseId", bindHouseId);
        List<Map> list = baseMapper.search(page, params);
        if (list.size() == 0) {
            return page.setRecords(list);
        }
        String skuIds = "";
        for (Map map : list) {
            skuIds += "," + map.get("skuId");
        }

        skuIds = skuIds.substring(1);

        //库存数量
        List<Map> skuList = houseId != null && houseId != 0 ? repositoryCountService.getSkuNumByHouseId(skuIds, houseId) :
                bindHouseId != null && bindHouseId != 0 ? repositoryCountService.getSkuNumByHouseId(skuIds, bindHouseId) : repositoryCountService.getSkuNum(skuIds);
        Map<Long, BigDecimal> skuMap = new HashMap<>();
        for (Map<String, Object> tmp : skuList) {
            skuMap.put((Long) tmp.get("skuId"), (BigDecimal) tmp.get("skuNum"));
        }
        for (Map map : list) {
            map.put("skusNum", skuMap.get((Long) map.get("skuId")) == null ? 0 : skuMap.get((Long) map.get("skuId")).intValue());
        }

        //最早批次
        List<Map> batchList = repositoryDetailService.getSkuBatchCodeForOut(skuIds);
        Map<String, String> batchMap = new HashMap<>();
        for (Map<String, Object> tmp : batchList) {
            batchMap.put(tmp.get("skuId").toString(), (String) tmp.get("house"));
        }
        for (Map map : list) {
            map.put("house", batchMap.get(map.get("skuId").toString()));
        }

        //成本单价
        return page.setRecords(list);
    }

    @Override
    public Page searchForRelative(MyPage<MMateriel> page, String searchText, String searchCar, Long houseId, Long bindHouseId) {
        Map<String, Object> params = new HashMap<>();
        params.put("searchText", searchText);
        params.put("searchCar", searchCar);
        params.put("houseId", houseId);
        params.put("bindHouseId", bindHouseId);

        List<Map> list = baseMapper.searchForRelative(page, params);
        if (list.size() == 0) {
            return page.setRecords(list);
        }
        String skuIds = "";
        for (Map map : list) {
            skuIds += "," + map.get("skuId");
        }

        skuIds = skuIds.substring(1);

        //库存数量
        List<Map> skuList = houseId != null && houseId != 0 ? repositoryCountService.getSkuNumByHouseId(skuIds, houseId) :
                bindHouseId != null && bindHouseId != 0 ? repositoryCountService.getSkuNumByHouseId(skuIds, bindHouseId) : repositoryCountService.getSkuNum(skuIds);
        Map<Long, BigDecimal> skuMap = new HashMap<>();
        for (Map<String, Object> tmp : skuList) {
            skuMap.put((Long) tmp.get("skuId"), (BigDecimal) tmp.get("skuNum"));
        }
        for (Map map : list) {
            map.put("skusNum", skuMap.get((Long) map.get("skuId")) == null ? 0 : skuMap.get((Long) map.get("skuId")).intValue());
        }

        //最早批次
        List<Map> batchList = repositoryDetailService.getSkuBatchCodeForOut(skuIds);
        Map<String, String> batchMap = new HashMap<>();
        for (Map<String, Object> tmp : batchList) {
            batchMap.put(tmp.get("skuId").toString(), (String) tmp.get("house"));
        }
        for (Map map : list) {
            map.put("house", batchMap.get(map.get("skuId").toString()));
        }

        //成本单价
        return page.setRecords(list);
    }

    @Override
    public List queryInvMaterielList(Map map) {
        List<Map> list = this.baseMapper.queryInvMaterielList(map);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).put("name", list.get(i).get("goodsName") + " " + list.get(i).get("skuName"));
        }
        return list;
    }

    @Override
    public MMateriel selectNotTenantId(Long id, Long tenantId) {
        return this.baseMapper.selectNotTenantId(id,tenantId);
    }
}
